<template>
	<div class="comQuantizationInvestmentPopup_container">
		<van-popup
			v-model="popShow"
			closeable
			close-icon="close"
			position="bottom"
			:style="{ 'min-height': '65%' }"
			@close="popupClose"
		>
			<div class="padding-1">
				<div class="comQuantizationInvestmentPopup_container_title">
					{{ $t('投资') }}
				</div>
				<!-- 备选投资额度 -->
				<!-- <div class="comQuantizationInvestmentPopup_container_investment mb-2">
					<van-tabs type="card" v-model="InvestmentData.earningActive" duration="1" @change="changeTabs">
						<van-tab v-for="(item,index) in changeMoneyList" :key="index" :title="item.toString()" :name="item"></van-tab>
					</van-tabs>
				</div> -->
				<div class="comQuantizationInvestmentPopup_container_investment_title mb-0">
					<span>{{ $t('投资金额') }}</span>
					<!-- <span class="investment_title_sps">{{ $t('余额') }}：{{ InvestmentData.balance }}</span> -->
				</div>
				<div class="comQuantizationInvestmentPopup_container_input mb-1">
					<input type="number" v-model="InvestmentData.money"  :placeholder="$t('请输入投资金额')" @blur="inputMoneyBlur"/>
				</div>
				<div class="comQuantizationInvestmentPopup_container_selectSale padding-1 br-8 mb-2" @click="showCouponSelect">
					<div>{{$t("选择优惠卷")}}</div>
					<div class="selectSale_right">
						<span class="mr-0">{{couponName ? couponName : $t('请选择')}}</span>
						<img src="@/image/aiQuantization/indexTop/arrow.png" alt="">
					</div>
				</div>
				<div class="comQuantizationInvestmentPopup_container_investment_title mb-0">
					<span>{{ $t('支付方式') }}</span>
				</div>
				<div class="comQuantizationInvestmentPopup_container_radioGroup mb-3">
					<van-radio-group v-model="InvestmentData.modePayRadio">
						
							<van-cell clickable v-for="(item , index) in canSelectModeOfPay" :key="index" :title="item.name" @click="currencyClick(index)">
								<template #icon>
									<img :src="item.img" alt="">
								</template>
								<template #default>
									<span>{{ estimatedPayment(item) }}</span>
								</template>
								<template #right-icon>
									<van-radio :name="index" />
								</template>
							</van-cell>
					</van-radio-group>
				</div>

				<button class="comQuantizationInvestmentPopup_container_btn" @click="investmentConfirm">{{ $t("立即投资") }}</button>
			</div>
		</van-popup> 
		<van-dialog v-model="dialogShow" :title="$t('投资确认')" show-cancel-button @confirm="clickConfirm" :confirm-button-text="$t('确认投资')" :cancel-button-text="$t('我再想想')" confirm-button-color="#fff" cancel-button-color="#5D6B8C">
			<div class="comQuantizationInvestmentPopup_container_dialog_title">{{ $t("是否确认投资？") }}</div>
			<div class="comQuantizationInvestmentPopup_container_dialog_content">{{ $t("支付后无法撤销，请谨慎操作！") }}</div>
		</van-dialog>
		<div class="comQuantizationInvestmentPopup_coupon" v-if="couponShow">
			<van-nav-bar
				left-arrow
				@click-left="onClickLeft"
				class="mb-1"
			>
			</van-nav-bar>
			<div class="comQuantizationInvestmentPopup_coupon_box pl-1 pr-1">
				<div class="coupon_title mb-1">
					<span>{{$t("可使用优惠卷")}}</span>
					<button class="br-8 mr-0" v-if="!!radio" @click="radio = null">{{$t("取消")}}</button>
				</div>

				<div v-if="couponList.length">
					<van-radio-group v-model="radio" class="">
						<div class="coupon_list_item br-16 mb-0" v-for="(item , index) in couponList" :key="index" @click="radio = item.id">
							<div class="coupon_list_item_left">
								<div class="item_left_title">
									<span class="item_left_title_sps">{{ couponFunctionText(item) }}</span>
								</div>
								<div class="item_left_lavel" v-if="item.type != '3'">
									{{ couponLimitText(item) }}
								</div>
							</div>
							<div class="coupon_list_item_right pl-1 pr-1">
								<div class="right_content">
									<div class="right_content_title mb-1">{{item.name}}</div>
									<div class="right_content_lavel">{{item.start_time_day}}</div>
								</div>
								<div class="right_radio">
									<van-radio 
										:name="item.id"
									></van-radio>
								</div>
							</div>
						</div>
					</van-radio-group>
				</div>
				<van-empty v-else :image-size="100" :description="$t('暂无优惠卷')"></van-empty>
			</div>
		</div>
		<div class="comQuantizationInvestmentPopup_btnBox pr-1" v-if="couponShow">
			
			<button class="br-8" @click="changeCoupon">{{$t("确认")}}</button>
		</div>
		<div class="comQuantizationInvestmentPopup_btnBox_bg"></div>
	</div>
</template>
<script>
import { getInvestmentInfo , buyInvestment } from "@/request/aiQuantization"
import BusinessUtils from '@/utils/business';
export default {
	name: "ComQuantizationInvestmentPopup",
	props:{
		id:{
			default:''
		},
		data:{
			type:Object,
			default:()=>{}
		},
		show:{
			type:Boolean,
			default:false
		},
		popupClose:{
			type:Function,
			default:()=>{}
		},
		popCallBack:{
			type:Function,
			default:()=>{}
		},
		orderType: {
			type: Number,
			default: 1
		},
		money:{
			type:String,
			default:0
		}
	},
	data(){
		return{
			popShow:false,
			dialogShow:false,
			investmentAmount:'',
			InvestmentData:{
				earningActive:50,
				balance: 121511,
				money: 0,
				modePayRadio:0,
				modeOfPay: [],
				coupon: '', // 优惠卷id
				currencyId: '',
				id:''
			},
			couponShow: false, // 优惠卷展示
			couponList:[],
			radio: null, // 优惠卷选择
			changeMoneyList: [50, 100, 1000, 10000 ],
			couponName: '',
			coinItem: null,
			activeRadioID: null,

			max_amount: 0, // 最大投资额度
			min_amount: 0, // 最小投资额度
			quota: null, // 剩余额度
		}
	},
	computed:{
		canSelectModeOfPay() {
			if(this.InvestmentData.coupon !== ''){
				return this.InvestmentData.modeOfPay.filter(pay => pay.isCouponTarget)
			}else{
				return this.InvestmentData.modeOfPay
			}
		},
	},
	
	mounted(){
		this.getInvestmentInfo()
	},
	methods:{
		currencyClick(index){
			this.InvestmentData.modePayRadio = index
		},

		getInvestmentInfo(){
			// 获取对应投资信息
			getInvestmentInfo({}).then(res=>{
				if(res.code == 1){
					this.InvestmentData.modeOfPay = []
					res.data.icon.forEach((item,index)=>{
						this.InvestmentData.modeOfPay.push({
							img: BusinessUtils.getCoinIcon(item.name),
							id: item.id,
							name: item.name,
							price: Number(item.user_money).toFixed(4),
							originalPrice: Number(item.user_money).toFixed(4),
							isCouponTarget: false,
							rate_to_sat: item.rate_to_sat,
						})
					})
					if(this.orderType == 1){
						this.InvestmentData.money = Number(res.data.zhuanshu.min_amount).toFixed(0)
						this.min_amount = Number(res.data.zhuanshu.min_amount)
						this.max_amount = Number(res.data.zhuanshu.max_amount)
						this.changeMoneyList = this.generateFourValues(Number(res.data.zhuanshu.min_amount).toFixed(0), Number(res.data.zhuanshu.max_amount).toFixed(0))
					}else{
						let taocan = res.data.taocan.filter(item=>item.id == this.id)[0]
						if(taocan){
							this.max_amount = Number(taocan.max_amount)
							this.min_amount = Number(taocan.min_amount)
							this.quota = Number(taocan.quota)

							if(Number(this.InvestmentData.money) < this.min_amount){
								this.InvestmentData.money = String(this.min_amount.toFixed(0))
							}
							if(Number(this.InvestmentData.money) > this.max_amount){
								this.InvestmentData.money = String(this.max_amount.toFixed(0))
							}
							if(Number(this.InvestmentData.money) > this.quota){
								this.InvestmentData.money = String(this.quota.toFixed(0))
							}

							this.changeMoneyList = this.generateFourValues(res.data.taocan.filter(item=>item.id == this.id)[0].min_amount, res.data.taocan.filter(item=>item.id == this.id)[0].max_amount)
						}
					}
					console.log(this.changeMoneyList)
					this.couponList = res.data.coupon
				}
			})
		},
		generateFourValues(min, max) {
			min = Number(min);
			max = Number(max);
			
			// 如果范围太小，直接返回固定间隔
			if (max - min < 30) {
				return [min, min + 10, min + 20, max];
			}
			
			// 计算1/3和2/3位置的值
			const oneThird = min + (max - min) / 3;
			const twoThirds = min + (max - min) * 2 / 3;
			
			// 找到最接近的十的倍数
			const roundToTen = (num) => {
				return Math.round(num / 10) * 10;
			};
			
			let middle1 = roundToTen(oneThird);
			let middle2 = roundToTen(twoThirds);
			
			// 确保中间值不相同且有意义
			if (middle1 === middle2) {
				middle1 = Math.max(min, middle1 - 10);
				middle2 = Math.min(max, middle2 + 10);
			}
			
			// 确保中间值在min和max之间
			const adjustedMiddle1 = Math.max(min, Math.min(max, middle1));
			const adjustedMiddle2 = Math.max(min, Math.min(max, middle2));
			
			// 返回结果数组
			return [min, adjustedMiddle1, adjustedMiddle2, max];
		},
		resetData() {
			const originalData = this.$options.data.call(this);
			this.InvestmentData = {...originalData.InvestmentData};
			this.couponName = originalData.couponName;
			this.couponShow = originalData.couponShow;
			this.radio = originalData.radio;
		},

		inputMoneyBlur(){
			if(this.InvestmentData.money == ''){
				this.InvestmentData.money = '0'
			}
		},
		checkInvestmentAmount(){
			if(this.InvestmentData.money == '' || this.InvestmentData.money == undefined){
				this.$toast.fail(this.$t('请输入投资金额'))
				return false;
			}

			if(Number(this.InvestmentData.money) < this.min_amount){
				this.InvestmentData.money = this.min_amount.toFixed(0)
				this.$toast.fail(this.$t('最小投资额度') + " " + this.min_amount.toFixed(0))
				return false
			}
			if(Number(this.InvestmentData.money) > this.max_amount){
				this.InvestmentData.money = this.max_amount.toFixed(0)
				this.$toast.fail(this.$t('最大投资额度') + " " + this.max_amount.toFixed(0))
				return false
			}
			if(this.quota && Number(this.InvestmentData.money) > this.quota){
				this.InvestmentData.money = this.quota.toFixed(0)
				this.$toast.fail(this.$t('剩余额度') + " " + this.quota.toFixed(0))
				return false
			}
			return true;
		},


		investmentConfirm(){
			if(!this.checkInvestmentAmount()){
				return;
			}

			this.InvestmentData.id = this.id
			this.dialogShow = true;
		},
		clickConfirm(){
			let result = {
				id: this.InvestmentData.id,
				money: this.InvestmentData.money,
				currency: this.canSelectModeOfPay[this.InvestmentData.modePayRadio].id,
				coupon: this.InvestmentData.coupon,
			}

			this.popCallBack(result , 1)
			// 清空弹窗数据
			// this.InvestmentData = {
			// 	earningActive:50,
			// 	balance: 0,
			// 	money: '',
			// 	modePayRadio:1, // 1: SAT, 2: SUSD
			// 	id:''
			// }
		},
		showCouponSelect(){
			this.couponShow = true;
		},
		onClickLeft(){
			this.changeCoupon()
		},
		changeCoupon(){
			console.log(this.radio)
			this.couponShow = false;
			if(!this.radio){
				this.InvestmentData.coupon = ''
				this.couponName = ''
				this.coinItem = null
				this.InvestmentData.modeOfPay.forEach((item , index)=>{
					this.InvestmentData.modeOfPay[index] = {
						...item,
						isCouponTarget: false,
					}
				})
				return
			}
			this.InvestmentData.coupon = this.radio
			this.coinItem = this.couponList.filter(item=>item.id == this.radio)[0]
			this.couponName = this.coinItem.name
			
			// 在这处理优惠卷
			let arr = JSON.parse(JSON.stringify(this.InvestmentData.modeOfPay))
			this.InvestmentData.modeOfPay.forEach((item , index)=>{
				if(item.name == this.coinItem.currency_name){
					arr[index] = {
						...item,
						// originalPrice: item.price,
						// price: item.price ,

						isCouponTarget: true,
					}
				}else{
					// if(item.originalPrice){
					// 	arr[index] = {
					// 		...item,
					// 		price: item.originalPrice,
					// 		originalPrice: null
					// 	}
					// }
					arr[index] = {
						...item,

						isCouponTarget: false,
					}
				}
			})
			this.InvestmentData.modeOfPay = arr
		},
		changeTabs(name , title){
			console.log(name , title)
			this.InvestmentData.money = name
		},

		// 预估支付金额
		estimatedPayment(currency) {
			let originalSUSD = Number(this.InvestmentData.money);
			let susdCount = originalSUSD
			if(this.couponName != ''){
				if (currency.isCouponTarget) {
					if(this.coinItem.type == "1"){// 抵扣
						susdCount = originalSUSD - Number(this.coinItem.sub_money);
						if(susdCount < 0){
							susdCount = 0;
						}
					}else if(this.coinItem.type == "2"){// 折扣
						susdCount = originalSUSD*(1-Number(this.coinItem.sub_rate)/100)
						if(susdCount < 0){
							susdCount = 0;
						}
					} else if(this.coinItem.type == "3"){// 体验
						susdCount = 0
					}
				} else {
					susdCount = originalSUSD;
				}
			}

			let estimatedMoney = susdCount * Number(currency.rate_to_sat);
			return estimatedMoney.toFixed(4);
		},
		//优惠券功能文字
		couponFunctionText(coupon) {
			if (coupon.type === '1') {
				let moneyText = Number(coupon.sub_money).toFixed(0)+' '+coupon.currency_name
				return this.$t('抵扣 {money}', { money: moneyText });
			} else if (coupon.type === '2') {
				let rate = Number(coupon.sub_rate).toFixed(0);
				return this.$t('抵扣 {rate}%',{ rate: rate });
			} else if (coupon.type === '3') {
				return this.$t('体验套餐');
			} else {
				return '';
			}
		},

		couponLimitText(coupon) {
			if (coupon.type === '1' || coupon.type === '2') {
				return this.$t('满 {amount} 可用', { amount: Number(coupon.use_money).toFixed(0) });
			} else {
				return '';
			}
		}
	},
	watch:{
		show(newVal){
			this.popShow = newVal;
			this.resetData()
			if(newVal == true){
				this.InvestmentData.money = this.money
			}
			this.getInvestmentInfo()
		},
		orderType(newVal){
			// this.getInvestmentInfo()
		},
		canSelectModeOfPay(newVal) {
			if(this.InvestmentData.modePayRadio >= newVal.length) {
				this.InvestmentData.modePayRadio = 0;
			}
		},
	},
};
</script>

<style>
@import './index.less';

</style>